<?php
namespace app\api\controller\search;

use app\common\controller\Api;
use think\Db;

class Search extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 搜索
     * @path api/search/Search/searchHot
     */
    public function search()
    {
        $userId = $this->auth->id;
        $page = $this->request->param('page',1);
        $name = $this->request->param('name','');
        $minPrice = $this->request->param('min_price',0);
        $maxPrice = $this->request->param('max_price',99999);

        $sort = $this->request->param('sort', 'comprehensive'); // 默认综合排序
        $order = $this->request->param('order', 'DESC'); // 默认为降序
        $storeId = $this->auth->store_id;

        $orderS = "";

        $user = db('user')->where('id',$userId)->find();
        $notGoods = db('store')->where('id',$storeId)->value('not_goods');

        $ids = [];
        if (!empty($notGoods)) {
            $ids = trim($notGoods);
        }
        $whereHaving = "";
        $where = [];
        $where['is_on_sale'] = 1;
        $where['id'] = ['not in',$ids];
        if (!empty($name)) {
            $where['goods_name'] = ['like',"%".$name.'%'];
        }

        // 价格筛选
        $selectField = "price";
        if ($user['type'] == 2) {
            //高级用户
            $selectField = "ROUND(highuser_discount/100*price,2)";//
        } elseif ($user['type'] == 3) {
            //合伙人
            $selectField = "ROUND(partner_discount/100*price,2)";//
        }

        $minPrice = $minPrice ? $minPrice : 0;
        $maxPrice = $maxPrice ? $maxPrice : 999999;
        if ($minPrice > $maxPrice) {
            $this->error('最小金额不能高于最大金额');
        }
        if ($minPrice > 0 || $maxPrice < 999999) {
            $whereHaving = $selectField." BETWEEN '{$minPrice}' AND '{$maxPrice}'";
        }

        // 排序逻辑
        switch ($sort) {
            case 'collection_num':
                $orderS = "collection_num ".$order;
                break;
            case 'cashsale':
                $orderS = "(cashsale+salecount) ".$order;
                break;
            case 'price':
                $orderS = $selectField." ".$order;
                break;
            case 'comprehensive':
                // 综合排序：收藏量+销量+价格（这里假设先按收藏量，再按销量，最后按价格，均为降序）
                $orderS = 'collection_num DESC, cashsale DESC, price DESC';
                break;
            default:
                // 默认综合排序
                $orderS = 'collection_num DESC, cashsale DESC, price DESC';
        }


        //var_dump($whereHaving);die;
        $goods = db('goods')
            ->field("id,goods_name,image,spec_name,price,line_price,ROUND(highuser_discount/100*price,2) AS heigh_price,ROUND(partner_discount/100*price,2) AS partner_price")
            ->where($where)
            ->where($whereHaving)
            ->orderRaw($orderS)
            ->paginate(10, false, ['page' => $page]);
//        var_dump(db()->getLastSql());die;
        $goods = $goods->toArray();
        $goods['data'] = goodsPriceReset($goods['data'],$this->auth->type);
        $goods['data'] = addWebSiteUrl($goods['data'],['image']);
        $backList = [
            'goods'=>$goods,
        ];
        //记录搜索内容
        $searchHistory = Db::name("search_history")->where(['name'=>$name,'user_id'=>$userId])->find();
        if (empty($searchHistory)) {
            Db::name("search_history")->insert([
                'user_id'=>$userId,
                'name'=>$name,
                'add_time'=>time()
            ]);
        } else {
            Db::name("search_history")->where(['name'=>$name,'user_id'=>$userId])->update([
                'add_time'=>time()
            ]);
        }
        $this->success('请求成功',$backList);
    }

    /**
     * 搜索历史
     * @ApiMethod (POST)
     * @path api/search/search/searchHistory
     */
    public function searchHistory()
    {
        $user_id = $this->auth->id;
        $where = "user_id = {$user_id} and name != ''";
        $field = "id,name";
        $order = "add_time DESC";
        $list = Db::name("search_history")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /**
     * 删除搜索历史
     * @ApiMethod (POST)
     * @path api/search/search/delSearchHistory
     */
    public function delSearchHistory()
    {
        $user_id = $this->auth->id;
        $search_id = $this->request->post('search_id');
        $where = "user_id = {$user_id}";
        if($search_id){
            $where.= " AND id = {$search_id}";
        }
        Db::name("search_history")->where($where)->delete();
        $this->success("删除成功");
    }

    /**
     * 搜索热词
     * @path api/search/Search/searchHot
     */
    public function searchHot()
    {
        $searchHot = db('config')->where('name','search_hot_word')->find();
        $searchHot = $searchHot['value'] ? explode('，',$searchHot['value']) : [];
        $backList = [
            'searchHot'=>$searchHot,
        ];
        $this->success('请求成功',$backList);
    }
}
